package top.as.sean.common.ip2region;

import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 * 用于查询ip归属地
 *
 * @author: ArchieSean
 * @create: 2023/2/9
 */
@Slf4j
@Component
public class Ip2regionUtils {
    /**
     * 查询对象
     */
    private static Searcher searcher;

    /**
     * ip2region.xdb 文件路径
     */
    private static final String DB_PATH = "ip2region.xdb";

    /**
     * 本地局域网
     */
    private static final String LOCAL1 = "127.0.0.1";

    private static final String LOCAL2 = "192.168";

    /**
     * 本地局域网
     */
    private static final String LOCAL_NAME = "本地局域网";

    @PostConstruct
    public void init() {
        log.info("---初始化ip归属地查询对象开始---");
        try {
            ClassPathResource resource = new ClassPathResource(DB_PATH);
            InputStreamReader reader = new InputStreamReader(resource.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(reader);
            String collect = bufferedReader.lines().collect(Collectors.joining("\n"));
            File file = ResourceUtils.getFile(DB_PATH);
            String dbPath = file.getPath();
            searcher = Searcher.newWithBuffer(dbPath.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("--初始化ip归属地查询对象异常--");
        }
        log.info("---初始化ip归属地查询对象结束---");
    }

    /**
     * 根据ip获取ip归属地
     *
     * @param ip 真实ip
     * @return str
     */
    public String getIpHome(String ip) {
        if (ip.equals(LOCAL1) || ip.startsWith(LOCAL2)) {
            return LOCAL_NAME;
        }
        String search = "";
        try {
            search = searcher.search(ip);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return search;
    }
}
